package groupTalk;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class ClientDemo1 {
    public static void main(String[] args) throws Exception {
        //实现TCP通信下多发多收：客户端开发
        System.out.println("==客户端启动==");
        //1.创建Socket对象，构造方法中绑定服务器的IP地址和端口号
        Socket socket = new Socket("127.0.0.1",9999);
        //2.获取一个输出流，写数据
        OutputStream os = socket.getOutputStream();
        //3.使用特殊的数据流，写数据
        DataOutputStream dos = new DataOutputStream(os);
        //键盘录入对象
        Scanner sc = new Scanner(System.in);

        InputStream is = socket.getInputStream();
        DataInputStream dis = new DataInputStream(is);
        //写数据
        new Thread(){
            public void run(){
                while (true) {
                    try {
                        System.out.println("请说：");
                        String msg = sc.next();
                        if("exit".equals(msg)){
                            System.out.println("==客户端退出==");
                            dos.close();
                            socket.close();
                            break;
                        }
                        dos.writeUTF(msg);//发送数据
                        dos.flush();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
        }.start();

        //读数据
        new Thread(() -> {
            while (true) {
                String s = null;
                try {
                    s = dis.readUTF();
                    System.out.println("收到群里的消息：" + s);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}
